package com.woniuxy.mesboot.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.mesboot.util.JwtUtils;
import com.woniuxy.mesboot.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ：lisir
 * @date ：Created in 2023/5/30 10:34
 * @description：认证成功走该处理类
 */
public class LoginAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    @Autowired
    private JwtUtils jwtUtils;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        //后面授权时使用
        SecurityContextHolder.getContext().setAuthentication(authentication);
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String token = jwtUtils.generateToken(loginUser.getUsername());
        String value = new ObjectMapper().writeValueAsString(Result.ok().data("menuList",loginUser.getMenuVOS()).data("user",loginUser.getUser()).data("token",token));
        response.getWriter().println(value);
    }
}
